<?php

namespace TpAmis\Traits;

use TpAmis\Admin;
use TpAmis\Renderers\BaseApi;
use TpAmis\Support\Cores\AdminPipeline;
use TpAmis\Tools\File;

trait ElementTrait
{
    protected string $PrimaryKey = 'id';

    /**
     * 基础页面
     *
     * @return \TpAmis\Renderers\Page
     */
    protected function basePage()
    {
        return amis()->Page()->className('m:overflow-auto');
    }

    /**
     * 返回列表按钮
     *
     * @return \TpAmis\Renderers\OtherAction
     */
    protected function backButton()
    {
        $path   = str_replace(config('admin.route.prefix'), '', request()->url());
        $script = sprintf('window.$owl.hasOwnProperty(\'closeTabByPath\') && window.$owl.closeTabByPath(\'%s\')', $path);

        $action = amis()->OtherAction()
            ->label(admin_trans('admin.back'))
            ->icon('fa-solid fa-chevron-left')
            ->level('primary')
            ->onClick('window.history.back();'.$script);

        return $action; //   return AdminPipeline::handle(AdminPipeline::PIPE_BACK_ACTION, $action);
    }


    /**
     * 批量删除按钮
     */
    protected function bulkDeleteButton()
    {
        $action = amis()->DialogAction()
            ->label(admin_trans('删除'))
            ->icon('fa-solid fa-trash-can')
            ->dialog(
                amis()->Dialog()
                    ->title(admin_trans('删除'))
                    ->className('py-2')
                    ->actions([
                        amis()->Action()->actionType('cancel')->label(admin_trans('admin.cancel')),
                        amis()->Action()->actionType('submit')->label(admin_trans('删除'))->level('danger'),
                    ])
                    ->body([
                        amis()->Form()->wrapWithPanel(false)->api($this->getBulkDeletePath())->body([
                            amis()->Tpl()->className('py-2')->tpl(admin_trans('admin.confirm_delete')),
                        ]),
                    ])
            );
        if (! authamis($this->getBulkDeletePath())) {
            return $action->disabled(true);
        }
        return $action; //AdminPipeline::handle(AdminPipeline::PIPE_BULK_DELETE_ACTION, $action);
    }

    public function AjaxButton(string $title = '', $url = '', $options = [])
    {
        $action = $this->customButton($title, "AjaxAction");

        foreach ($options as $key => $option) {
            //添加自定义参数，
            $action->$key($option);
        }
        $trueUrl = '';
        if (is_string($url)) {
            $urlCheck = explode(':', $url);
            if (count($urlCheck) == 1) {
                $action->api($url);
            } else {
                $action->api($urlCheck[1]);
            }
        } elseif (is_array($url)) {
            $action->api($url['api']);
        } else if (is_object($url)) {
            $action->api($url);
        } else {
            $action->disabled(true);
        }

        if (! authamis($trueUrl)) {
            $action->disabled(true);
        }

        if (! authamis($this->getCreatePath())) {
            return $action->disabled(true);
        }
        return $action;
    }

    public function AjaxFormButton($label = '提交', $url)
    {
        return amis()->AjaxAction()->label($label)->api($url);

    }

    public function BaseApiDelete($thinkUrl, array $vars = [], $suffix = true, $domain = false)
    {
        return $this->BaseApi($thinkUrl, 'delete', $vars, $suffix, $domain);
    }

    public function BaseApiPut($thinkUrl, array $vars = [], $suffix = true, $domain = false)
    {
        return $this->BaseApi($thinkUrl, 'put', $vars, $suffix, $domain);
    }

    public function BaseApiPost($thinkUrl, array $vars = [], $suffix = true, $domain = false)
    {
        return $this->BaseApi($thinkUrl, 'post', $vars, $suffix, $domain);
    }

    public function BaseApiGet($thinkUrl, array $vars = [], $suffix = true, $domain = false)
    {
        return $this->BaseApi($thinkUrl, 'get', $vars, $suffix, $domain);
    }

    public function BaseApi($thinkUrl, $method = 'post', array $vars = [], $suffix = true, $domain = false)
    {
        return amis()->BaseApi()->method($method)->url(adminUrl($thinkUrl, $vars, $suffix, $domain))->dataType('form');
    }

    public function LinkButton($title, $url, $icon = '', $level = '')
    {
        $title  = $title ?: '链接';
        $action = $this->customButton($title, 'LinkAction', $icon, $level);
        $action->link($url);

        if (! authamis($url)) {
            return $action->disabled(true);
        }
        return $action;
    }

    public function UrlButton($title, $url, $blank = true, $icon = '', $level = '')
    {
        $title  = $title ?: '链接';
        $action = $this->customButton($title, 'UrlAction', $icon, $level);
        $action->url($url)->blank($blank);
        if (! authamis($url)) {
            return $action->disabled(true);
        }
        return $action;
    }

    /**
     * Summary of DialogIframeButton
     * @param string $title
     * @param mixed $url
     * @param string $dialogSize      * Dialog 大小 可选值: xs | sm | md | lg | xl | full
     * @param mixed $icon
     * @return \TpAmis\Renderers\DialogAction
     */
    public function DialogIframeButton(string $title = '', $url = 'form', string $dialogSize = 'full', $icon = '')
    {
        $title = $title ?: '';

        $form   = amis()->IFrame()->src($url);
        $action = amis()->DialogAction()->dialog(
            amis()->Dialog()->title($title)->body($form)->size($dialogSize)->actions([])
        );

        $action->label($title)->level('primary');
        if ($icon) {
            $action->icon(true);
        }
        if (! authamis($url)) {
            return $action->disabled();
        }
        return $action;
    }

    public function DrawerButton(string $title = '', $formMonth = 'form', string $dialogSize = 'md', $icon = '')
    {

        if (is_callable($formMonth)) {
            $form = call_user_func($formMonth);
        } else if (is_string($formMonth)) {
            $form = $this->$formMonth();
        } else {
            $form = $this->baseForm();
        }

        $form = $form->canAccessSuperData(false)->api($this->getStorePath())->onEvent([]);

        $action = amis()->DrawerAction()->drawer(
            amis()->Drawer()->title($title)->body($form)->size($dialogSize)
        );

        $action->label($title)->level('primary');
        if ($icon) {
            $action->icon(true);
        }
        if (! authamis($this->getCreatePath())) {
            return $action->disabled();
        }
        return $action;
    }

    public function DialogButton(string $title = '弹窗', $formMonth = 'form', string $dialogSize = 'md', $icon = '')
    {
        $title = $title ?: '';

        if (is_callable($formMonth)) {
            $form = call_user_func($formMonth);
        } else if (is_string($formMonth)) {
            $form = $this->$formMonth();
        } else {
            $form = $this->baseForm();
        }

        // $form = $form->canAccessSuperData(false)->api($this->getStorePath())->onEvent([]);


        $action = amis()->DialogAction()->dialog(
            amis()->Dialog()->title($title)->body($form)->size($dialogSize)
                ->actions([amis()->Button()->actionType('submit')->primary(true)->label($title)])
        );


        $action->label($title)->level('primary');
        if ($icon) {
            $action->icon(true);
        }
        if (! authamis($this->getCreatePath())) {
            return $action->disabled();
        }
        return $action;
    }

    /**
     * 新增按钮
     *
     * @param  $dialog     是否弹窗, 弹窗: true|dialog, 抽屉: drawer,
     * @param string $title 弹窗标题 & 按钮文字, 默认: 新增
     *
     * @return \TpAmis\Renderers\DialogAction|\TpAmis\Renderers\LinkAction
     */
    protected function customButton(string $title = '', string $ActionName = '', $icon = '', $level = 'primary')
    {
        $title = $title ?: '自定义按钮';

        $action = amis()->$ActionName()->label($title);
        $action->label($title)->icon($icon)->level($level);

        return $action;
    }

    /**
     * 新增按钮
     *
     * @param  $dialog     是否弹窗, 弹窗: true|dialog, 抽屉: drawer,
     * @param string $dialogSize 弹窗大小, 默认: md, 可选值: xs | sm | md | lg | xl | full
     * @param string $title 弹窗标题 & 按钮文字, 默认: 新增
     *
     * @return \TpAmis\Renderers\DialogAction|\TpAmis\Renderers\LinkAction
     */
    protected function createButton($dialog = true, string $dialogSize = 'md', string $title = '', $formMonth = 'form')
    {
        $title = $title ?: '新增';

        $action = amis()->LinkAction()->link($this->getCreatePath());

        if ($dialog) {
            $form = $this->$formMonth()->canAccessSuperData(false)->api($this->getStorePath())->onEvent([]);
            if ($dialog === 'iframe') {
                $form   = amis()->IFrame()->src($this->getCreatePath('create', [], true, true));
                $action = amis()->DialogAction()->dialog(

                    amis()->Dialog()->title($title)->body($form)->size($dialogSize)
                );
            } else if ($dialog === 'drawer') {
                $action = amis()->DrawerAction()->drawer(
                    amis()->Drawer()->title($title)->body($form)->size($dialogSize)
                );
            } else {
                $action = amis()->DialogAction()->dialog(

                    amis()->Dialog()->title($title)->body($form)->size($dialogSize)
                        ->actions([amis()->Button()->actionType('submit')->primary(true)->label($title)])
                );
            }
        }

        $action->label($title)->icon('fa fa-add')->level('primary');
        if (! authamis($this->getCreatePath())) {
            return $action->disabled(true);
        }
        return $action; // return AdminPipeline::handle(AdminPipeline::PIPE_CREATE_ACTION, $action);
    }

    /**
     * 行编辑按钮
     *
     * @param  $dialog     是否弹窗, 弹窗: true|dialog, 抽屉: drawer,
     * @param string $dialogSize 弹窗大小, 默认: md, 可选值: xs | sm | md | lg | xl | full
     * @param string $title 弹窗标题 & 按钮文字, 默认: 编辑
     *
     * @return \TpAmis\Renderers\DialogAction|\TpAmis\Renderers\LinkAction
     */
    protected function rowEditButton($dialog = false, string $dialogSize = 'md', string $title = '', $formMonth = 'form')
    {
        $title  = $title ?: '编辑';
        $action = amis()->LinkAction()->link($this->getEditPath());

        if ($dialog) {
            $form = $this->$formMonth(true)
                ->api($this->getUpdatePath())
                ->initApi($this->getEditGetDataPath())
                ->redirect('')
                ->onEvent([]);

            if ($dialog === 'drawer') {
                $action = amis()->DrawerAction()->drawer(
                    amis()->Drawer()->title($title)->body($form)->size($dialogSize)
                );
            } else {
                $action = amis()->DialogAction()->dialog(
                    amis()->Dialog()->title($title)->body($form)->size($dialogSize)
                );
            }
        }

        $action->label($title)->level('link');
        if (! authamis($this->getEditPath())) {
            return $action->disabled(true);
        }
        return $action;
    }

    /**
     * 行编辑按钮
     *
     * @param  $dialog     是否弹窗, 弹窗: true|dialog, 抽屉: drawer,
     * @param string $dialogSize 弹窗大小, 默认: md, 可选值: xs | sm | md | lg | xl | full
     * @param string $title 弹窗标题 & 按钮文字, 默认: 编辑
     *
     * @return \TpAmis\Renderers\DialogAction|\TpAmis\Renderers\LinkAction
     */
    protected function rowEditerButton(string $dialogSize = 'md', string $title = '', $primaryKey = 'id')
    {
        $title = $title ?: '编辑';
        // adminUrl('edit', [$primaryKey => '${'.$primaryKey.'}'])
        $IFrame = amis()->IFrame()->src($this->getCreatePath('edit', [$primaryKey => '${'.$primaryKey.'}'], true, true));
        $action = amis()->DialogAction()->dialog(
            amis()->Dialog()->title($title)->body($IFrame)->size($dialogSize)->actions([])
        );

        $action->label($title)->level('link');
        if (! authamis($this->getEditPath())) {
            return $action->disabled(true);
        }
        return $action;
    }

    /**
     * 行详情按钮
     *
     * @param  $dialog     是否弹窗, 弹窗: true|dialog, 抽屉: drawer
     * @param string $dialogSize 弹窗大小, 默认: md, 可选值: xs | sm | md | lg | xl | full
     * @param string $title 弹窗标题 & 按钮文字, 默认: 详情
     *
     * @return \TpAmis\Renderers\DialogAction|\TpAmis\Renderers\LinkAction
     */
    protected function rowShowButton($dialog = false, string $dialogSize = 'md', string $title = '')
    {
        $title  = $title ?: admin_trans('admin.show');
        $action = amis()->LinkAction()->link($this->getShowPath());

        if ($dialog) {
            if ($dialog === 'drawer') {
                $action = amis()->DrawerAction()->drawer(
                    amis()->Drawer()->title($title)->body($this->detail('$id'))->size($dialogSize)
                );
            } else {
                $action = amis()->DialogAction()->dialog(
                    amis()->Dialog()->title($title)->body($this->detail('$id'))->size($dialogSize)
                );
            }
        }

        $action->label($title)->level('link');
        if (! authamis($this->getShowPath())) {
            return $action->disabled(true);
        }
        return $action; // return AdminPipeline::handle(AdminPipeline::PIPE_SHOW_ACTION, $action);
    }

    /**
     * 行删除按钮
     *
     * @param string $title
     *
     * @return \TpAmis\Renderers\DialogAction
     */
    protected function rowDeleteButton(string $title = '')
    {
        $action = amis()->DialogAction()
            ->label($title ?: '删除')
            ->className('text-danger')
            ->dialog(
                amis()->Dialog()
                    ->title()
                    ->className('py-2')
                    ->actions([
                        amis()->Action()->actionType('cancel')->label('取消'),
                        amis()->Action()->actionType('submit')->label('删除')->level('danger'),
                    ])
                    ->body([
                        amis()->Form()->wrapWithPanel(false)->api($this->getDeletePath())->body([
                            amis()->Tpl()->className('py-2')->tpl('确认删除'),
                        ]),
                    ])
            );
        if (! authamis($this->getDeletePath())) {
            return $action->disabled(true);
        }
        return $action;
    }

    /**
     * 操作列
     *
     * @param  $dialog     是否弹窗, 弹窗: true|dialog, 抽屉: drawer
     * @param string $dialogSize 弹窗大小, 默认: md, 可选值: xs | sm | md | lg | xl | full
     *
     * @return \TpAmis\Renderers\Operation
     */
    protected function rowActions($dialog = false, string $dialogSize = 'md')
    {
        if (is_array($dialog)) {
            return amis()->Operation()->label('操作')->buttons($dialog);
        }

        $actions = amis()->Operation()->label('操作')->buttons([
            $this->rowShowButton($dialog, $dialogSize),
            $this->rowEditButton($dialog, $dialogSize),
            $this->rowDeleteButton(),
        ]);

        return $actions;
    }

    /**
     * 基础筛选器
     *
     * @return \TpAmis\Renderers\Form
     */
    protected function baseFilter()
    {
        $schema = amis()->Form()
            ->panelClassName('base-filter')
            ->title('')
            ->actions([
                amis()->Button()->label('重置')->actionType('clear-and-submit'),
                amis('submit')->label('搜索')->level('primary'),
            ]);

        return $schema; //  return AdminPipeline::handle(AdminPipeline::PIPE_BASE_FILTER, $schema);
    }

    /**
     * 基础筛选器 - 条件构造器
     *
     * @return \TpAmis\Renderers\ConditionBuilderControl
     */
    protected function baseFilterConditionBuilder()
    {
        return amis()->ConditionBuilderControl('filter_condition_builder');
    }
    protected $headerToolbar = [];

    public function setHeaderToolbar($headerToolbar)
    {
        $this->headerToolbar[] = $headerToolbar;
        return $this;
    }
    /**
     * @return \TpAmis\Renderers\CRUDTable
     */
    protected function baseCRUD()
    { 
        $headerToolbar = array_merge($this->headerToolbar, $this->baseHeaderToolBar());
        $crud          = amis()->CRUDTable()
            ->perPageField('list_rows')
            ->perPage(10)
            ->alwaysShowPagination()
            ->affixHeader(false)
            // ->autoFillHeight(true)
            ->filterTogglable()
            ->filterDefaultVisible(false)
            ->api($this->getListGetDataPath())
            ->quickSaveApi($this->getQuickEditPath())
            ->quickSaveItemApi($this->getQuickEditPath())
            ->bulkActions([$this->bulkDeleteButton()])
            ->perPageAvailable([10, 15, 20, 25, 50, 100])
            ->footerToolbar(['switch-per-page', 'statistics', 'pagination'])
            ->headerToolbar($headerToolbar);

        if (isset($this->service)) {
            $crud->set('primaryField', $this->getPrimaryKey());
        }

        return $crud; //  return AdminPipeline::handle(AdminPipeline::PIPE_BASE_CRUD, $crud);
    }

    /**
     * 获取主键
     * @return string
     */
    public function getPrimaryKey(): string
    {
        return $this->PrimaryKey;
    }

    /**
     * 获取主键
     * @param $PrimaryKey
     * @return string
     */
    public function setPrimaryKey($PrimaryKey): string
    {
        return $this->PrimaryKey = $PrimaryKey;
    }

    /**
     * 基础顶部工具栏
     *
     * @return array
     */
    protected function baseHeaderToolBar()
    {
        $schema = [
            
            amis('bulkActions')->align('left'),
            amis('export-excel')->align('right'),
            amis('reload')->align('right'),
            amis('filter-toggler')->align('right'),
        ];

        return $schema; //  return AdminPipeline::handle(AdminPipeline::PIPE_BASE_HEADER_TOOLBAR, $schema);
    }

    /**
     * 基础表单
     *
     * @param bool $back
     *
     * @return \TpAmis\Renderers\Form
     */
    protected function baseForm(bool $back = true)
    {

        $form = amis()->Form()->title(' ')->promptPageLeave();
        if ($back) {
            $form->onEvent([
                'submitSucc' => [
                    'actions' => [
                        ['actionType' => 'custom', 'script' => 'window.history.back()'],
                    ],
                ],
            ]);
        }
        return $form;
        // return AdminPipeline::handle(AdminPipeline::PIPE_BASE_FORM, $form);
    }

    /**
     * @return \TpAmis\Renderers\Form
     */
    protected function baseDetail()
    {
        $schema = amis()->Form()
            ->panelClassName('px-48 m:px-0')
            ->title(' ')
            ->mode('horizontal')
            ->actions([])
            ->initApi($this->getShowGetDataPath());
        return $schema;
        // return AdminPipeline::handle(AdminPipeline::PIPE_BASE_DETAIL, $schema);
    }

    /**
     * 基础列表
     *
     * @param $crud
     *
     * @return \TpAmis\Renderers\Page
     */
    protected function baseList($crud)
    {
        return amis()->Page()->className('m:overflow-auto pb-48')->body($crud);
    }

    /**
     * 导出按钮
     *
     * @param bool $disableSelectedItem
     *
     * @return \TpAmis\Renderers\Service
     */
    protected function exportAction($disableSelectedItem = false)
    {
        // 获取主键名称
        $primaryKey = $this->service->primaryKey();
        // 下载路径
        $downloadPath = admin_url('_download_export', true);
        // 导出接口地址
        $exportPath = $this->getExportPath();
        // 无数据提示
        $pageNoData = admin_trans('admin.export.page_no_data');
        // 选中行无数据提示
        $selectedNoData = admin_trans('admin.export.selected_rows_no_data');
        // 按钮点击事件
        // $event = fn($script) => ['click' => ['actions' => [['actionType' => 'custom', 'script' => $script]]]];
        $event = function ($script) {
            return [
                'click' => [
                    'actions' => [
                        ['actionType' => 'custom', 'script' => $script]
                    ]
                ]
            ];
        };
        // 导出处理动作
        $doAction = "doAction([{actionType:'setValue',componentId:'export-action',args:{value:{showExportLoading:true}}},{actionType:'ajax',args:{api:{url:url.toString(),method:'get'}}},{actionType:'setValue',componentId:'export-action',args:{value:{showExportLoading:false}}},{actionType:'custom',expression:'\${event.data.responseResult.responseStatus===0}',script:'window.open(\'{$downloadPath}?path=\'+event.data.responseResult.responseData.path)'}])";
        // 按钮
        $buttons = [
            // 导出全部
            amis()->VanillaAction()->label(admin_trans('admin.export.all'))->onEvent(
                $event("let data=event.data;let params=Object.keys(data).filter(key=>key!=='page' && key!=='__super').reduce((obj,key)=>{obj[key]=data[key];return obj;},{});let url=new URL('{$exportPath}',window.location.origin);Object.keys(params).forEach(key=>url.searchParams.append(key,params[key]));{$doAction}")
            ),
            // 导出本页
            amis()->VanillaAction()->label(admin_trans('admin.export.page'))->onEvent(
                $event("let ids=event.data.items.map(item=>item.{$primaryKey});if(ids.length===0){return doAction({actionType:'toast',args:{msgType:'warning',msg:'{$pageNoData}'}})};let url=new URL('{$exportPath}',window.location.origin);url.searchParams.append('_ids',ids.join(','));{$doAction}")
            ),
        ];
        // 导出选中项
        if (! $disableSelectedItem) {
            $buttons[] = amis()->VanillaAction()->label(admin_trans('admin.export.selected_rows'))->onEvent(
                $event("let ids=event.data.selectedItems.map(item=>item.{$primaryKey});if(ids.length===0){return doAction({actionType:'toast',args:{msgType:'warning',msg:'{$selectedNoData}'}})};let url=new URL('{$exportPath}',window.location.origin);url.searchParams.append('_ids',ids.join(','));{$doAction}")
            );
        }

        $action = amis()->Service()
            ->id('export-action')
            ->set('align', 'right')
            ->set('data', ['showExportLoading' => false])
            ->body(
                amis()->Spinner()->set('showOn', '${showExportLoading}')->overlay()->body(
                    amis()->DropdownButton()
                        ->label(admin_trans('admin.export.title'))
                        ->set('icon', 'fa-solid fa-download')
                        ->buttons($buttons)
                        ->closeOnClick()
                        ->align('right')
                )
            );
        if (! authamis($this->getExportPath())) {
            return $action->disabled(true);
        }
        return $action; //   return AdminPipeline::handle(AdminPipeline::PIPE_EXPORT_ACTION, $action);
    }

    protected function FileManager()
    {

        return amis()->Page()->regions([
            '0' => 'body',
        ])->id('u:14e60c296775')->pullRefresh([
                    'disabled' => '1',
                ])->body([
                    amis()->Flex()->items([
                        amis()->Container()->body([
                            amis()->TreeControl()->label('树组件')->name('tree')->options([
                                [
                                    'label' => '选项A',
                                    'value' => 'A',
                                    'children' => [
                                        [
                                            'label' => '选项C',
                                            'value' => 'C',
                                        ],
                                        [
                                            'label' => '选项D',
                                            'value' => 'D',
                                        ],
                                    ],
                                ],
                                [
                                    'label' => '选项B',
                                    'value' => 'B',
                                ],
                            ])->id('u:7dae8b587cad')->multiple('')->enableNodePath('')->hideRoot('1')->showIcon('1')->initiallyOpen('1'),
                        ])->size('none')->style([
                                    'position' => 'static',
                                    'display' => 'block',
                                    'flex' => '1 1 auto',
                                    'flexGrow' => '1',
                                    'flexBasis' => '0',
                                ])->wrapperBody('')->isFixedHeight('')->isFixedWidth('')->id('u:20b299ad1577'),
                        amis()->Container()->body([
                            amis()->ListControl()->label('列表')->name('list')->options([
                                [
                                    'label' => '选项A',
                                    'value' => 'A',
                                ],
                                [
                                    'label' => '选项B',
                                    'value' => 'B',
                                ],
                            ])->id('u:be6289ec2122'),
                        ])->size('none')->style([
                                    'position' => 'static',
                                    'display' => 'block',
                                    'flex' => '1 1 auto',
                                    'flexGrow' => '3',
                                    'flexBasis' => '0px',
                                ])->wrapperBody('')->isFixedHeight('')->isFixedWidth('')->id('u:ead5482608c5'),
                    ])->style([
                                'position' => 'relative',
                                'rowGap' => '10px',
                                'columnGap' => '10px',
                                'flexWrap' => 'nowrap',
                                'inset' => 'auto',
                            ])->id('u:beee00fc2f22')->isFixedHeight('')->isFixedWidth(''),
                ]);
    }
}
